package com.iwhalecloud.bss.kite.cucc.service.goods;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.iwhalecloud.bss.hsf.baseinf.service.InfExchangeService;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.common.constant.*;
import com.iwhalecloud.bss.kite.common.util.*;
import com.iwhalecloud.bss.kite.cucc.client.api.goods.IGoodsPriceFactorService;
import com.iwhalecloud.bss.kite.cucc.client.api.goods.IGoodsService;
import com.iwhalecloud.bss.kite.cucc.client.api.inf.IInfServiceBus;
import com.iwhalecloud.bss.kite.cucc.client.api.order.IOrderService;
import com.iwhalecloud.bss.kite.cucc.client.dto.goods.*;
import com.iwhalecloud.bss.kite.cucc.client.dto.goods.factor.PriceFactorDTO;
import com.iwhalecloud.bss.kite.cucc.common.callclient.HttpsCallClient;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalCallClientEnum;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalDcPublicConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalErrorConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.CommonUtil;
import com.iwhalecloud.bss.kite.cucc.dataservice.cache.CuccOfferOriginalInfoCache;
import com.iwhalecloud.bss.kite.cucc.service.inf.InfServiceHelper;
import com.iwhalecloud.bss.kite.cucc.service.util.CallClientUtils;
import com.iwhalecloud.bss.kite.cucc.service.util.GoodsPriceFactorUtil;
import com.iwhalecloud.bss.kite.cucc.service.util.LocalTokenUtil;
import com.iwhalecloud.bss.kite.cucc.spec.impl.transfer.GoodsInfoTransfer;
import com.iwhalecloud.bss.kite.cucc.spec.impl.transfer.ProductsInfoTransfer;
import com.iwhalecloud.bss.kite.dataservice.cache.*;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.LatestAccept;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.OfferCollection;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.ProdAttr;
import com.iwhalecloud.bss.kite.dataservice.mapper.spec.LatestAcceptMapper;
import com.iwhalecloud.bss.kite.dataservice.mapper.spec.OfferCollectionMapper;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.ztesoft.bss.common.exception.BssException;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;
import com.ztesoft.bss.common.util.StringUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class GoodsService implements IGoodsService {

    @Autowired
    private IGoodsPriceFactorService goodsPriceFactorService;

    @Autowired
    private IInfServiceBus infServiceBus;

    @Override
    public List<GoodsCategroyInfoDTO> queryGoodsCategroyInfo(String goodsProvince) {
        String catJsonStr = getCatJsonStr(goodsProvince);
        Map<String, Object> catMap = JSON.parseObject(catJsonStr, Map.class);
        Map<String, Object> resultBodyMap = (Map<String, Object>) catMap.get("UNI_BSS_BODY");
        Map<String, String> goodsCategroyInfoRsp = (Map<String, String>) resultBodyMap.get("GOODS_CATEGROY_INFO_RSP");
        List<GoodsCategroyInfoDTO> list = Lists.newArrayList();
        if (KiteMapUtils.isNotEmpty(goodsCategroyInfoRsp)) {
            list = JsonUtils.parseArray(goodsCategroyInfoRsp.get("data"), GoodsCategroyInfoDTO.class);

            // 过滤不需要在商品选择页展示的商品分类（过滤收入归集集团） 收入归集集团需求
            removeNotShowGoods(list);
        }

        return list;
    }

    @Override
    public List<GoodsDTO> queryGoodsListInCategroy(String categroyCode, String goodsName) {
        return this.queryGoodsListInCategroy(categroyCode, goodsName, ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr());
    }

    @Override
    public List<GoodsDTO> queryGoodsListInCategroy(String categroyCode, String goodsName, String provinceId) {
        Map<String, Object> uniBssBody = new HashMap<>();
        Map<String, Object> salegoodslistincategroyReq = new HashMap<>();
        salegoodslistincategroyReq.put("CATEGROY_CODE", categroyCode);
        salegoodslistincategroyReq.put("GOODS_NAME", goodsName);
        salegoodslistincategroyReq.put("ISSALE_GOODS_TYPE", "true");
        salegoodslistincategroyReq.put("TOUCH_POINT", "24");
        salegoodslistincategroyReq.put("province", provinceId);
        uniBssBody.put("SALEGOODSLISTINCATEGROY_REQ", salegoodslistincategroyReq);
        Map<String, Object> param = LocalTokenUtil.getParamMap(uniBssBody);
        param.put("OP_CODE", "json_jike_orderCenter_saleGoodsListInCategroy");
        InfServiceHelper.adaptGray(param, salegoodslistincategroyReq);
        String goodsJsonStr;
        if (CallClientUtils.callByHttp()) {
            goodsJsonStr = HttpsCallClient.postStringWithObject(LocalCallClientEnum.INF_COMMON_URL.getCenterCode(),
                LocalCallClientEnum.INF_COMMON_URL.getServiceCode(), param, LocalTokenUtil.getHeaderMap());
        }
        else {
            InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
            goodsJsonStr = infExchangeService.exchange(new JSONObject(param));
        }

        Map<String, Object> goodsMap = JSON.parseObject(goodsJsonStr, Map.class);
        Map<String, Object> resultBodyMap = (Map<String, Object>) goodsMap.get("UNI_BSS_BODY");
        Map<String, String> goodsListInCategroyRsp = (Map<String, String>) resultBodyMap
            .get("SALEGOODSLISTINCATEGROY_RSP");
        List<GoodsDTO> list = JsonUtils
            .parseArray(KiteMapUtils.getString(goodsListInCategroyRsp, "data"), GoodsDTO.class);

        // 五大双线落地方产品，只能通过代办进入订购页面，不能在选择商品页面选择，过滤
        if (KiteObjectUtils.isEmpty(categroyCode)) {
            String cateIdNotShow = DcPublicCache.getCodea(LocalDcPublicConsts.DC_20210422001, LocalDcPublicConsts.SELECT_GOODS_NOT_SHOW_CATE_ID);
            if(KiteStringUtils.isNotEmpty(cateIdNotShow)) {
                list.removeIf(cloudGood -> KiteStringUtils.equalsAny(cloudGood.getCateId(), cateIdNotShow.split(",")));
            }
        }
        // 五大上线落地方产品-数字化，商品不展示，按商品编码过滤
        String goodsSkuNotShow = DcPublicCache.getCodeb(LocalDcPublicConsts.DC_20210422001, LocalDcPublicConsts.SELECT_GOODS_NOT_SHOW_CATE_ID);
        if(KiteStringUtils.isNotEmpty(goodsSkuNotShow)) {
            list.removeIf(cloudGood -> KiteStringUtils.equalsAny(cloudGood.getGoodsSku(), goodsSkuNotShow.split(",")));
        }

        // 在业务订购当中不能订购云账号商品
        //list.removeIf(cloudGood -> KiteStringUtils.equalsAny(cloudGood.getCateId(), "2000998", "2100982", "2100983"));
        // 获取登录的操作员工号
        String userId = ContextUtil.getSimpleLoginInfo().getUserId() + "";
        //获取当前工号下所有收藏商品
        List<OfferCollection> allOfferCollections = OfferCollectionCache.get(userId);
        //是否收藏
        if (KiteListUtils.isNotEmpty(allOfferCollections) && KiteListUtils.isNotEmpty(list)) {
            list.stream().forEach(dto -> {
                String offerId = dto.getGoodsSku();
                allOfferCollections.stream().forEach(collection -> {
                    String favoriteOfferId = collection.getOfferId();
                    if (KiteStringUtils.isEqual(offerId, favoriteOfferId)) {
                        dto.setIsFavorite("T");
                    }
                });
            });
        }

        //是否最近受理
        List<LatestAccept> accepts = LatestAcceptCache.get(userId);
        if (KiteListUtils.isNotEmpty(accepts)) {
            accepts = accepts.stream().sorted(Comparator.comparing(LatestAccept::getUpdateDate).reversed())
                .collect(Collectors.toList());
            if (accepts.size() > 9) {
                accepts = accepts.subList(0, 9);
            }
            accepts.stream().forEach(accept -> list.stream().forEach(dto -> {
                String offerId = dto.getGoodsSku();
                String acceptOfferId = accept.getOfferId();
                if (KiteStringUtils.isEqual(offerId, acceptOfferId)) {
                    dto.setIsLatestAccept("T");
                }
            }));
        }
        if (KiteObjectUtils.isEmpty(categroyCode)) {
            for (Iterator<GoodsDTO> it = list.iterator(); it.hasNext(); ) {//大数据商品业务订购的受理入口必须从商机转定菜单进入，不能通过业务受理菜单进入受理。
                GoodsDTO map = it.next();
                String cateid = map.getCateId();
                if (!KiteObjectUtils.isEmpty(DcPublicCache.get("202104161623", cateid))) {
                    it.remove();
                }
            }
        }
        return list;
    }

    @Override
    public DataResult<String> queryGoodPrice(GoodPriceReqDTO goodPriceReqDTO) {
        String resPrice = "暂无价格";
        // 计价因子查询
        List<PriceFactorDTO> priceFactors = goodsPriceFactorService.getPriceFactors(goodPriceReqDTO.getSKU());
        // 将计价因子放到询价请求中
        GoodsPriceFactorUtil.transform(goodPriceReqDTO, priceFactors);
        // 询价
        Map feeMap = infServiceBus.queryGoodPrice(goodPriceReqDTO).getResultObject();
        if (Objects.isNull(feeMap)) {
            return ErrorConsts.SUCCESS.getResult(resPrice);
        }
        if (KiteMapUtils.isNotEmpty(feeMap) && KiteListUtils.isNotEmpty((List<?>) feeMap.get("feeItemPrice"))) {
            double amount = 0;
            List<Map> feeItemPrices = (List<Map>) feeMap.get("feeItemPrice");
            for (Map map : feeItemPrices) {
                String price = KiteMapUtils.getString(map, "price");
                if (StringUtils.isNotEmpty(price)) {
                    amount = amount + Double.parseDouble(price);
                }
            }
            resPrice = String.format("%.2f", amount);
        }
        return ErrorConsts.SUCCESS.getResult(resPrice);
    }

    @Override
    public List<GoodsDTO> queryBaseGoodsInfoNew(String goodsName, String categroyCode) {
        Map<String, Object> uniBssBody = new HashMap<>();
        Map<String, Object> goodsListInCategroyReq = new HashMap<>();
        goodsListInCategroyReq.put("CATEGROY_CODE", categroyCode);
        goodsListInCategroyReq.put("GOODS_NAME", goodsName);
        goodsListInCategroyReq.put("TOUCH_POINT", "24");
        uniBssBody.put("GOODS_LIST_IN_CATEGROY_REQ", goodsListInCategroyReq);
        Map<String, Object> param = LocalTokenUtil.getParamMap(uniBssBody);
        param.put("OP_CODE", "json_jike_orderCenter_goodsListInCategroy");
        InfServiceHelper.adaptGray(param, goodsListInCategroyReq);
        String goodsJsonStr;
        if (CallClientUtils.callByHttp()) {
            goodsJsonStr = HttpsCallClient.postStringWithObject(LocalCallClientEnum.INF_COMMON_URL.getCenterCode(),
                LocalCallClientEnum.INF_COMMON_URL.getServiceCode(), param, LocalTokenUtil.getHeaderMap());
        }
        else {
            InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
            goodsJsonStr = infExchangeService.exchange(new JSONObject(param));
        }
        Map<String, Object> goodsMap = JSON.parseObject(goodsJsonStr, Map.class);
        Map<String, Object> resultBodyMap = (Map<String, Object>) goodsMap.get("UNI_BSS_BODY");
        Map<String, String> goodsListInCategroyRsp = (Map<String, String>) resultBodyMap
            .get("GOODS_LIST_IN_CATEGROY_RSP");
        List<GoodsDTO> goodsDTOs = JsonUtils
            .parseArray(KiteMapUtils.getString(goodsListInCategroyRsp, "data"), GoodsDTO.class);
        return goodsDTOs;
    }

    @Override
    public Map<String, Object> queryGoodsByOfferId(String goodsSku) {
        return queryGoodsByOfferIdAndProvince(goodsSku, ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr());
    }

    @Override
    public Map<String, Object> queryGoodsByOfferIdAndProvince(String goodsSku) {
        return queryGoodsByOfferIdAndProvince(goodsSku, ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr());
    }

    @Override
    public Map<String, Object> queryGoodsByOfferIdAndProvince(String goodsSku, String provinceId) {
        Map<String, Object> uniBssBody = new HashMap<>();
        Map<String, Object> requestParamReq = new HashMap<>();
        requestParamReq.put("REQUEST_ID", RandomStringUtils.randomNumeric(18));
        requestParamReq.put("GOODS_SKU", goodsSku);
        requestParamReq.put("USE_CASE", DcSystemParamCache.getDcParamVal("prod_his_use_case"));
        requestParamReq.put("TOUCH_PLATFORM", "24");
        requestParamReq.put("TOUCH_PROVINCE", provinceId);
        uniBssBody.put("REQUEST_PARAM_REQ", requestParamReq);
        Map<String, Object> param = LocalTokenUtil.getParamMap(uniBssBody);
        param.put("OP_CODE", "json_jike_orderCenter_requestParam");
        InfServiceHelper.adaptGray(param, requestParamReq);
        String goodsJsonStr;
        if (CallClientUtils.callByHttp()) {
            goodsJsonStr = HttpsCallClient.postStringWithObject(LocalCallClientEnum.INF_COMMON_URL.getCenterCode(),
                LocalCallClientEnum.INF_COMMON_URL.getServiceCode(), param, LocalTokenUtil.getHeaderMap());
        }
        else {
            InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
            goodsJsonStr = infExchangeService.exchange(new JSONObject(param));
        }
        Map<String, Object> goodsMap = JSON.parseObject(goodsJsonStr, Map.class);
        Map<String, Object> resultBodyMap = (Map<String, Object>) goodsMap.get("UNI_BSS_BODY");
        Map<String, String> requestParamRsp = (Map<String, String>) resultBodyMap.get("REQUEST_PARAM_RSP");
        Map<String, Object> goodsInfoDTO = JsonUtils
            .parseObject(KiteMapUtils.getString(requestParamRsp, "data"), Map.class);
        return goodsInfoDTO;
    }

    @Override
    public DataResult<List<AttrDTO>> queryGoodKeyAttrs(String goodsSku) {
        Offer offer = OfferCache.get(goodsSku);
        List<AttrDTO> result = new ArrayList<>();
        if (Objects.isNull(offer)) {
            return ErrorConsts.SUCCESS.getResult(result);
        }
        if (KeyConsts.OFFER_TYPE_11.equals(offer.getOfferType())) {
            Map good = queryGoodsByOfferId(goodsSku);
            if (good != null) {
                List<Map> goodsAttrs = (List<Map>) good.get("goodsAttrs");
                if (KiteListUtils.isNotEmpty(goodsAttrs)) {
                    goodsAttrs.forEach(map -> {
                        AttrDTO attrDTO = KiteMapUtils.mapToBean(map, AttrDTO.class);
                        if (attrDTO.isKeyAttr()) {
                            attrDTO.setGoodsSku(offer.getOfferId());
                            result.add(attrDTO);
                        }
                    });
                }
            }
        }
        else if (KeyConsts.OFFER_TYPE_13.equals(offer.getOfferType())) {
            Map good = queryGoodsByOfferId(goodsSku);
            if (good != null) {
                List<Map> saleGoods = (List<Map>) good.get("saleGoods");
                if (KiteListUtils.isNotEmpty(saleGoods)) {
                    Map<String, AttrDTO> attrDTOMap = new HashMap<>();
                    saleGoods.forEach(singleGood -> {
                        List<Map> goodsAttrs = (List<Map>) singleGood.get("goodsAttrs");
                        if (KiteListUtils.isNotEmpty(goodsAttrs)) {
                            goodsAttrs.forEach(map -> {
                                AttrDTO attrDTO = JSONObject.parseObject(JSONObject.toJSON(map).toString(), AttrDTO.class);
                                if (attrDTO.isKeyAttr()) {
                                    attrDTO.setGoodsSku(KiteMapUtils.getString(singleGood, "goodsSku"));
                                    dealLinkRule(map, attrDTO);
                                    addAttrDTO(attrDTOMap, attrDTO);
                                }
                            });
                        }
                    });
                    attrDTOMap.forEach((s, attrDTO) -> result.add(attrDTO));
                }
            }
        }
        return ErrorConsts.SUCCESS.getResult(result);
    }

    @SuppressWarnings("unchecked")
    @Override
    public DataResult<List<AttrDTO>> queryGoodsAttrsByProvince(String goodsSku) {
        Offer offer = OfferCache.get(goodsSku);
        List<AttrDTO> result = new ArrayList<>();
        if (Objects.isNull(offer)) {
            return ErrorConsts.SUCCESS.getResult(result);
        }
        if (KeyConsts.OFFER_TYPE_13.equals(offer.getOfferType())) {
            Map good = queryGoodsByOfferIdAndProvince(goodsSku);
            if (good != null) {
                List<Map> saleGoods = (List<Map>) good.get("saleGoods");
                if (KiteListUtils.isNotEmpty(saleGoods)) {
                    String singleGoodsSku = (String) saleGoods.get(0).get("goodsSku");
                    String goodsType = (String) saleGoods.get(0).get("goodsType");
                    Map<String, Object> goodsOriginalInfo = CuccOfferOriginalInfoCache.get(singleGoodsSku);
                    if (KiteStringUtils.equals("group", goodsType)) {
                        // 暂不支持批量融合场景-查询属性
                        BssException.throwOut("", "", "暂不支持融合商品的批量配置");
                        /*List<Map<String, Object>> goodsCategroys = (List<Map<String, Object>>) goodsOriginalInfo
                            .get("goodsCategroy");
                        for (Map<String, Object> goodsCategroy : goodsCategroys) {
                            List<Map<String, Object>> goodsMaps = (List<Map<String, Object>>) goodsCategroy
                                .get("goods");
                        }*/
                    }
                    else {
                        List<Map<String, Object>> productCategroys = (List<Map<String, Object>>) goodsOriginalInfo
                            .get("productCategroy");
                        if (KiteListUtils.isNotEmpty(productCategroys)) {
                            for (Map<String, Object> productCategroy : productCategroys) {
                                if ("base".equals(KiteMapUtils.getString(productCategroy, "productType"))) {
                                    List<Map<String, Object>> products = (List<Map<String, Object>>) productCategroy
                                        .get("products");
                                    if (KiteListUtils.isNotEmpty(products)) {
                                        Map<String, Object> product = products.get(0);
                                        // 所有产品属性
                                        Map<String, AttrDTO> attrDTOMap = new HashMap<>();
                                        List<Map<String, Object>> prodAttrs = (List<Map<String, Object>>) product
                                            .get("productAttrs");
                                        prodAttrs.forEach(map -> {
                                            AttrDTO attrDTO = JSONObject.parseObject(JSONObject.toJSON(map).toString(), AttrDTO.class);
                                            //attrDTO.setGoodsSku(KiteMapUtils.getString(singleGood, "goodsSku"));
                                            dealLinkRule(map, attrDTO);
                                            addAttrDTO(attrDTOMap, attrDTO);
                                        });

                                        attrDTOMap.forEach((s, attrDTO) -> result.add(attrDTO));
                                        // 产品数字化修改
                                        List<ProdAttr> prodAttrConfigs = ProdAttrCache.get(KiteMapUtils.getString(product, "productCode"));
                                        if (!KiteListUtils.isEmpty(prodAttrConfigs)) {
                                            result.removeIf(attr -> !prodAttrConfigs.stream().map(ProdAttr::getFieldName).collect(Collectors.toList()).contains(attr.getAttrCode()));
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        return ErrorConsts.SUCCESS.getResult(result);
    }

    @Override
    public DataResult<List<AttrDTO>> queryGoodKeyAttrsByProvince(String goodsSku) {
        return this.queryGoodKeyAttrsByProvince(goodsSku, ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr());
    }

    @Override
    public DataResult<List<AttrDTO>> queryGoodKeyAttrsByProvince(String goodsSku, String provinceId) {
        Map goodsInfo = this.queryGoodsByOfferIdAndProvince(goodsSku, provinceId);
        Offer offer = GoodsInfoTransfer.convertOffer(goodsInfo);
        List<AttrDTO> result = new ArrayList<>();
        if (Objects.isNull(offer)) {
            return ErrorConsts.SUCCESS.getResult(result);
        }
        if (KeyConsts.OFFER_TYPE_11.equals(offer.getOfferType())) {
            Map good = queryGoodsByOfferIdAndProvince(goodsSku, provinceId);
            if (good != null) {
                List<Map> goodsAttrs = (List<Map>) good.get("goodsAttrs");
                if (KiteListUtils.isNotEmpty(goodsAttrs)) {
                    goodsAttrs.forEach(map -> {
                        AttrDTO attrDTO = KiteMapUtils.mapToBean(map, AttrDTO.class);
                        if (attrDTO.isKeyAttr()) {
                            attrDTO.setGoodsSku(offer.getOfferId());
                            result.add(attrDTO);
                        }
                    });
                }else {
                    List<Map> saleGoods = (List<Map>) good.get("saleGoods");
                    if (KiteListUtils.isNotEmpty(saleGoods)) {
                        // 部分产品，关键属性的部分枚举值，不在销售中心展示，在此过滤，仅展示配置枚举值
                        List<DcPublic> dcPublicList = DcPublicCache.getByPkey("2021060801", offer.getCateId());
                        Map<String, AttrDTO> attrDTOMap = new HashMap<>();
                        saleGoods.forEach(singleGood -> {
                            List<Map> goodAttrs = (List<Map>) singleGood.get("goodsAttrs");
                            if (KiteListUtils.isNotEmpty(goodAttrs)) {
                                goodAttrs.forEach(map -> {
                                    // AttrDTO attrDTO = KiteMapUtils.mapToBean(map, AttrDTO.class);
                                    AttrDTO attrDTO = JSONObject.parseObject(JSONObject.toJSON(map).toString(), AttrDTO.class);
                                    if (attrDTO.isKeyAttr()) {
                                        attrDTO.setGoodsSku(KiteMapUtils.getString(singleGood, "goodsSku"));
                                        filterAttrValues(attrDTO, dcPublicList);
                                        dealLinkRule(map, attrDTO);
                                        addAttrDTO(attrDTOMap, attrDTO);
                                    }
                                });
                            }
                        });
                        attrDTOMap.forEach((s, attrDTO) ->
                            result.add(attrDTO));
                    }
                }
            }
        }
        else if (KeyConsts.OFFER_TYPE_13.equals(offer.getOfferType())) {
            Map good = queryGoodsByOfferIdAndProvince(goodsSku, provinceId);
            if (good != null) {
                List<Map> saleGoods = (List<Map>) good.get("saleGoods");
                if (KiteListUtils.isNotEmpty(saleGoods)) {

                    // 部分产品，关键属性的部分枚举值，不在销售中心展示，在此过滤，仅展示配置枚举值
                    List<DcPublic> dcPublicList = DcPublicCache.getByPkey("2021060801", offer.getCateId());

                    Map<String, AttrDTO> attrDTOMap = new HashMap<>();
                    saleGoods.forEach(singleGood -> {
                        List<Map> goodsAttrs = (List<Map>) singleGood.get("goodsAttrs");
                        if (KiteListUtils.isNotEmpty(goodsAttrs)) {
                            goodsAttrs.forEach(map -> {
                                // AttrDTO attrDTO = KiteMapUtils.mapToBean(map, AttrDTO.class);
                                AttrDTO attrDTO = JSONObject.parseObject(JSONObject.toJSON(map).toString(), AttrDTO.class);
                                if (attrDTO.isKeyAttr()) {
                                    attrDTO.setGoodsSku(KiteMapUtils.getString(singleGood, "goodsSku"));
                                    filterAttrValues(attrDTO, dcPublicList);
                                    dealLinkRule(map, attrDTO);
                                    addAttrDTO(attrDTOMap, attrDTO);
                                }
                            });
                        }
                    });
                    attrDTOMap.forEach((s, attrDTO) ->
                        result.add(attrDTO));
                }
            }
        }
        result.forEach((attrDTO)->{
            if (attrDTO.isKeyAttr()){
                if (CollectionUtils.isNotEmpty(attrDTO.getAttrValues())&& attrDTO.getAttrValues().size()==1){
                    attrDTO.setDefaultAttrValCodes(attrDTO.getAttrValues().get(0).getValueCode());
                }
            }
        });
        return ErrorConsts.SUCCESS.getResult(result);
    }

    /**
     * 产品关键属性，部分不在销售中心展示，在此过滤
     */
    private static void filterAttrValues(AttrDTO attrDTO, List<DcPublic> dcPublicList) {
        if(dcPublicList != null && dcPublicList.size() > 0) {
            String attrCode = attrDTO.getAttrCode();
            for (DcPublic dcPublic : dcPublicList) {
                if(dcPublic.getPcode().equals(attrCode)) {
                    String [] values = dcPublic.getCodea().split(SymbolConsts.COMMA);
                    List<AttrValuesDTO> attrValues = attrDTO.getAttrValues().stream().filter(attrValuesDTO ->
                        KiteStringUtils.equalsAny(attrValuesDTO.getValueCode(), values)).collect(Collectors.toList());
                    attrDTO.setAttrValues(attrValues);
                    attrDTO.setAttrValCodes(dcPublic.getCodea());
                    break;
                }
            }
        }
    }

    private void dealLinkRule(Map map, AttrDTO attrDTO) {
        if (KiteMapUtils.isNotEmpty(map)) {
            Map<String, Object> attrMap = JSON.parseObject(map.toString(), Map.class);
            if (KiteMapUtils.isNotEmpty(attrMap) && !KiteObjectUtils.isEmpty(attrMap.get("linkRule"))) {
                LinkRule linkRule = new LinkRule();
                List<ValueLinksDTO> valueLinksList = Lists.newArrayList();
                Map<String, Object> linkRuleMap = JSON.parseObject(attrMap.get("linkRule").toString(), Map.class);
                linkRule.setParentAttr(KiteMapUtils.getString(linkRuleMap, "parentAttr"));
                if (KiteMapUtils.isNotEmpty(linkRuleMap)) {
                    List<Map> valueLinkList = (List<Map>) JSON
                        .parseObject(KiteMapUtils.getString(linkRuleMap, "valueLinks"), List.class);
                    if (KiteListUtils.isNotEmpty(valueLinkList)) {
                        valueLinkList.stream().forEach(valueLink -> {
                            ValueLinksDTO valueLinksDTO = KiteMapUtils.mapToBean(valueLink, ValueLinksDTO.class);
                            valueLinksList.add(valueLinksDTO);
                        });
                    }
                }
                linkRule.setValueLinks(valueLinksList);
                attrDTO.setLinkRules(linkRule);
            }
        }
    }

    @Override
    public DataResult<List<AttrDTO>> queryGoodAttrs(String goodsSku) {
        Offer offer = OfferCache.get(goodsSku);
        List<AttrDTO> result = new ArrayList<>();
        if (Objects.isNull(offer)) {
            return ErrorConsts.SUCCESS.getResult(result);
        }
        if (KeyConsts.OFFER_TYPE_11.equals(offer.getOfferType())) {
            Map good = queryGoodsByOfferId(goodsSku);
            if (good != null) {
                List<Map> goodsAttrs = (List<Map>) good.get("goodsAttrs");
                if (KiteListUtils.isNotEmpty(goodsAttrs)) {
                    goodsAttrs.forEach(map -> {
                        AttrDTO attrDTO = KiteMapUtils.mapToBean(map, AttrDTO.class);
                        attrDTO.setGoodsSku(offer.getOfferId());
                        result.add(attrDTO);
                    });
                }
            }
        }
        else if (KeyConsts.OFFER_TYPE_13.equals(offer.getOfferType())) {
            Map good = queryGoodsByOfferId(goodsSku);
            if (good != null) {
                List<Map> saleGoods = (List<Map>) good.get("saleGoods");
                if (KiteListUtils.isNotEmpty(saleGoods)) {
                    Map<String, AttrDTO> attrDTOMap = new HashMap<>();
                    saleGoods.forEach(singleGood -> {
                        List<Map> goodsAttrs = (List<Map>) singleGood.get("goodsAttrs");
                        if (KiteListUtils.isNotEmpty(goodsAttrs)) {
                            goodsAttrs.forEach(map -> {
                                AttrDTO attrDTO = JSONObject.parseObject(JSONObject.toJSON(map).toString(), AttrDTO.class);
                                attrDTO.setGoodsSku(KiteMapUtils.getString(singleGood, "goodsSku"));
                                addAttrDTO(attrDTOMap, attrDTO);
                            });
                        }
                    });
                    attrDTOMap.forEach((s, attrDTO) -> result.add(attrDTO));
                }
            }
        }
        return ErrorConsts.SUCCESS.getResult(result);
    }

    @Override
    public DataResult<List<GoodsMemberDTO>> queryGoodsMember(String goodsSku) {
        Map goodsMap = CuccOfferOriginalInfoCache.get(goodsSku);
        if (KiteMapUtils.isEmpty(goodsMap)) {
            goodsMap = queryGoodsByOfferId(goodsSku);
        }
        List<GoodsMemberDTO> goodsMemberDTOList = new ArrayList<>();
        //获取收发端成员
        if (KiteObjectUtils.isEmpty(goodsMap)) {
            LocalErrorConsts.GOODS_IS_NULL.throwOut(goodsSku);
        }
        if (KiteObjectUtils.isEmpty(goodsMap.get("members"))) {
            return ErrorConsts.SUCCESS.getResult(goodsMemberDTOList);
        }
        String members = goodsMap.get("members").toString();
        goodsMemberDTOList = JsonUtils.parseArray(members, GoodsMemberDTO.class);
        List<Map> members_his = ProductsInfoTransfer.getHistoryDataByNode(goodsMap, "members", null);
        packInValidMemCate(members_his,goodsMemberDTOList);
        String unfoldCatIds = DcPublicCache.getCodea(LocalKeyConsts.UNFOLD_DISPLAY_MEMBER_GOODS, goodsSku);
        goodsMemberDTOList.forEach(goodsMemberDTO -> {
            goodsMemberDTO.setMax(StringUtil.isEmpty(goodsMemberDTO.getMax())  ? "1": goodsMemberDTO.getMax());
            goodsMemberDTO.setMin(StringUtil.isEmpty(goodsMemberDTO.getMin()) ? "0": goodsMemberDTO.getMin());
            if (KiteStringUtils.isEqual("0", goodsMemberDTO.getMax())) {
                goodsMemberDTO.setMax("1");
            }
            if(KiteStringUtils.isEmpty(goodsMemberDTO.getStatusCd())){
                goodsMemberDTO.setStatusCd(KeyConsts2.PROD_STATUS_HIS_00A);
            }
            for (MemberGoodDTO memberGoodDTO : goodsMemberDTO.getMemberGoods()) {
                if (KiteStringUtils.equals(memberGoodDTO.getCateId(),LocalKeyConsts.ORIGINATOR_CATE_ID)) {
                    memberGoodDTO.setRoleId(LocalKeyConsts.ORIGINATOR_ROLE_ID);
                }
                else if (KiteStringUtils.equals(memberGoodDTO.getCateId(),LocalKeyConsts.RECEIVER_CATE_ID)) {
                    memberGoodDTO.setRoleId(LocalKeyConsts.RECEIVER_ROLE_ID);
                }
                if (StringUtil.isEmpty(memberGoodDTO.getMax())) {
                    memberGoodDTO.setMax(goodsMemberDTO.getMax());
                    memberGoodDTO.setMin("0");
                }
                if (KiteStringUtils
                    .isIndexOf(unfoldCatIds, memberGoodDTO.getCateId(), LocalKeyConsts.COMMA_SPLIT_FLAG)) {
                    memberGoodDTO.setUnfold(LocalKeyConsts.IFTRUE_T);
                }
                else {
                    memberGoodDTO.setUnfold(LocalKeyConsts.IFTRUE_F);
                }
            }
            //goodsMemberDTO.getMemberGoods().get(0).getCateId().equals("");
        });
        return ErrorConsts.SUCCESS.getResult(goodsMemberDTOList);
    }

    @Override
    public List<Map<String, Object>> queryFavoriteGoodsList(String goodsName) {
        List<Map<String, Object>> list = new ArrayList<>();
        // 获取登录的操作员工号
        String userId = ContextUtil.getSimpleLoginInfo().getUserId() + "";
        //获取当前工号下所有收藏商品
        List<OfferCollection> allOfferCollections = OfferCollectionCache.get(userId);
        if (KiteListUtils.isNotEmpty(allOfferCollections)) {
            // 在业务订购当中不能订购云账号商品和大数据商品
            allOfferCollections.removeIf(allOfferCollection -> KiteStringUtils
                .equalsAny(allOfferCollection.getCateId(), "2000998", "2100982", "2100983", "2000816", "2000817",
                    "2000873", "2000865", "2000866", "2000862", "2000863", "2000864"));
            Set<String> set = new HashSet<>();
            allOfferCollections.stream().forEach(collection -> {
                String cateId = collection.getCateId();
                set.add(cateId);
            });
            set.stream().forEach(cateId -> {
                List<Map<String, Object>> offerList = new ArrayList<>();
                Map<String, Object> result = new HashMap<>();
                allOfferCollections.stream().forEach(col -> {
                    Map<String, Object> resultOfferMap = new HashMap<>();
                    String childCateId = col.getCateId();
                    if (KiteStringUtils.isEqual(cateId, childCateId)) {
                        result.put("cateId", cateId);
                        result.put("cateName", col.getCateName());
                        resultOfferMap.put("offerId", col.getOfferId());
                        resultOfferMap.put("offerName", col.getOfferName());
                        offerList.add(resultOfferMap);
                    }
                });
                result.put("offerList", offerList);
                list.add(result);
            });
        }
        return list;
    }

    @Override
    public Map<String, Object> operateFavoritesOffers(String offerId, String actionType) {
        Map<String, Object> restMap = new HashMap();
        try {
            OfferCollectionMapper offerCollectionMapper = SpringUtil.getBean(OfferCollectionMapper.class);
            Offer offer = OfferCache.get(offerId);
            if (null == offer) {
                ErrorConsts.OFFER_NOT_FOUND.throwOut();
            }
            Map<String, Object> offerMap = offer.getOfferMap();
            // 获取登录的操作员工号
            String userId = ContextUtil.getSimpleLoginInfo().getUserId() + "";
            String postId = ContextUtil.getSimpleLoginInfo().getPostId() + "";
            String orgId = ContextUtil.getSimpleLoginInfo().getOrgId() + "";
            List<OfferCollection> allOfferCollections = OfferCollectionCache.get(userId);
            List<OfferCollection> thisOfferCollections = allOfferCollections.stream().filter(
                collection -> KiteStringUtils.isEqual(userId, collection.getCreateStaff()) && KiteStringUtils
                    .isEqual(offerId, collection.getOfferId())).collect(Collectors.toList());
            // 判斷是否已經存在
            if (Objects.equals(ActionType.A.name(), actionType)) {
                if (KiteListUtils.isEmpty(thisOfferCollections)) {
                    String collectionId = SeqUtils.getNext(TableConsts.OfferCollection);
                    OfferCollection offCollectionVo = new OfferCollection();
                    offCollectionVo.setCollectionId(collectionId);
                    offCollectionVo.setOfferId(offerId);
                    offCollectionVo.setOfferName(KiteMapUtils.getString(offerMap, "offerName"));
                    offCollectionVo.setCateId(KiteMapUtils.getString(offerMap, "cateId"));
                    offCollectionVo.setCateName(KiteMapUtils.getString(offerMap, "cateName"));
                    offCollectionVo.setStatusCd("1000");
                    offCollectionVo.setCreateStaff(userId);
                    offCollectionVo.setCreateOrgId(orgId);
                    offCollectionVo.setCreatePost(postId);
                    offCollectionVo.setUpdateStaff(userId);
                    offCollectionVo.setUpdateOrgId(orgId);
                    LocalDateTime now = LocalDateTime.now();
                    offCollectionVo.setStatusDate(now);
                    offCollectionVo.setCreateDate(now);
                    offCollectionVo.setUpdateDate(now);

                    allOfferCollections.add(offCollectionVo);
                    TransactionUtils.executeNew(() -> {
                        offerCollectionMapper.deleteOfferCollection(offerId, userId);
                        offerCollectionMapper.insert(offCollectionVo);
                    });
                }
                else {
                    ErrorConsts.OFFER_COLLECTION_ADD.throwOut();
                }
            }
            else if (Objects.equals(ActionType.D.name(), actionType)) {
                if (KiteListUtils.isEmpty(thisOfferCollections)) {
                    ErrorConsts.OFFER_COLLECTION_DEL.throwOut();
                }
                else {
                    Iterator<OfferCollection> it = allOfferCollections.iterator();
                    while (it.hasNext()) {
                        OfferCollection collection = it.next();
                        if (KiteStringUtils.isEqual(collection.getOfferId(), offerId)) {
                            it.remove();
                            break;
                        }
                    }
                    TransactionUtils.executeNew(() -> {
                        offerCollectionMapper.deleteOfferCollection(offerId, userId);
                    });
                }
            }
            OfferCollectionCache.getInst().defaultReloadObject(userId);
            restMap.put("ResultCode", "0");
            restMap.put("ResultMsg", "SUCCESS");
        }
        catch (Exception e) {
            restMap.put("ResultCode", "1");
            restMap.put("ResultMsg", e.getMessage());
        }
        return restMap;
    }

    @Override
    public Map<String, Object> operateLatestAcceptGoods(String staffId, String orgId, String postId,
        String sceneInstId) {
        Map<String, Object> restMap = new HashMap();
        try {
            IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
            List<KiteOfferInst> promOfferInsts;
            promOfferInsts = querySceneInstService.listPromotionOfferInsts(sceneInstId);
            if (KiteListUtils.isEmpty(promOfferInsts)) {
                promOfferInsts = Lists.newArrayList();
                KiteOfferInst offerInst = querySceneInstService.getMainOfferInst(sceneInstId);
                promOfferInsts.add(offerInst);
            }
            if (KiteListUtils.isNotEmpty(promOfferInsts)) {
                KiteOfferInst offerInst = promOfferInsts.get(0);
                List<LatestAccept> allLatestAccept = LatestAcceptCache.get(staffId);
                LatestAcceptMapper latestAcceptMapper = SpringUtil.getBean(LatestAcceptMapper.class);
                String offerId = querySceneInstService
                    .getExtParameterValue(sceneInstId, LocalKeyConsts.ACCEPT_GOODS_SPU);
                /*if (KiteStringUtils.isEmpty(offerId)) {
                    offerId = offerInst.getOfferId();
                }*/
                if (!KiteStringUtils.isEmpty(offerId)) {
                    String offerName = OfferCache.get(offerId).getOfferName();
                    List<LatestAccept> acceptlists = allLatestAccept.stream().filter(
                        accept -> KiteStringUtils.isEqual(offerId, accept.getOfferId()) && KiteStringUtils
                            .isEqual(staffId, accept.getCreateStaff())).collect(Collectors.toList());

                    if (KiteListUtils.isEmpty(acceptlists)) {
                        LocalDateTime now = LocalDateTime.now();
                        LatestAccept accept = new LatestAccept();
                        String acceptId = SeqUtils.getNext(TableConsts.LatestAccept);
                        accept.setAcceptId(acceptId);
                        accept.setOfferId(offerId);
                        accept.setOfferName(offerName);
                        accept.setStatusCd("1000");
                        accept.setCreateStaff(staffId);
                        accept.setCreateOrgId(orgId);
                        accept.setCreatePost(postId);
                        accept.setUpdateStaff(staffId);
                        accept.setUpdateOrgId(orgId);

                        accept.setStatusDate(now);
                        accept.setCreateDate(now);
                        accept.setUpdateDate(now);
                        KiteAttr attr = offerInst.getAttr("cateId");
                        accept.setCateId(OfferCache.get(offerId).getCateId());
                        TransactionUtils.executeNew(() -> {
                            latestAcceptMapper.deleteLatestAccept(offerId, staffId);
                            latestAcceptMapper.insert(accept);
                        });
                    }
                    else {
                        allLatestAccept.stream().forEach(accept -> {
                            LocalDateTime now = LocalDateTime.now();
                            if (KiteStringUtils.isEqual(offerId, accept.getOfferId())) {
                                String acceptId = accept.getAcceptId();
                                accept.setUpdateDate(now);
                                TransactionUtils.executeNew(() -> {
                                    latestAcceptMapper.updateLatestAcceptInfo(acceptId, staffId, offerId);
                                });
                            }
                        });
                    }
                }
                LatestAcceptCache.getInst().defaultReloadObject(staffId);
                restMap.put("ResultCode", "0");
                restMap.put("ResultMsg", "SUCCESS");
            }
            else {
                restMap.put("ResultCode", "1");
                restMap.put("ResultMsg", "fail");
            }
        }
        catch (Exception e) {
            restMap.put("ResultCode", "1");
            restMap.put("ResultMsg", e.getMessage());
        }
        return restMap;
    }

    @Override
    public List<GoodsDTO> queryLatestAcceptList() {
        List<GoodsDTO> resultList = new ArrayList<>();
        // 获取登录的操作员工号
        String userId = ContextUtil.getSimpleLoginInfo().getUserId() + "";
        //获取当前工号下所有收藏商品
        List<OfferCollection> allOfferCollections = OfferCollectionCache.get(userId);
        //是否最近受理
        List<LatestAccept> accepts = LatestAcceptCache.get(userId);
        if (KiteListUtils.isNotEmpty(accepts)) {
            // 在业务订购当中不能订购云账号商品
            accepts.removeIf(accept -> KiteStringUtils
                .equalsAny(accept.getCateId(), "2000998", "2100982", "2100983", "2000816", "2000817", "2000873",
                    "2000865", "2000866", "2000862", "2000863", "2000864"));

            // 五大上线落地方产品-数字化，商品不展示，按商品编码过滤
            String goodsSkuNotShow = DcPublicCache.getCodeb(LocalDcPublicConsts.DC_20210422001, LocalDcPublicConsts.SELECT_GOODS_NOT_SHOW_CATE_ID);
            if(KiteStringUtils.isNotEmpty(goodsSkuNotShow)) {
                accepts.removeIf(accept -> KiteStringUtils.equalsAny(accept.getOfferId(), goodsSkuNotShow.split(",")));
            }

            accepts = accepts.stream().filter(accept -> !KiteStringUtils.isEmpty(accept.getOfferId()))
                .collect(Collectors.toList());
            accepts = accepts.stream().sorted(Comparator.comparing(LatestAccept::getUpdateDate).reversed())
                .collect(Collectors.toList());
            if (accepts.size() > 9) {
                accepts = accepts.subList(0, 9);
            }
            accepts.stream().forEach(accept -> {
                GoodsDTO dto = new GoodsDTO();
                dto.setGoodsSku(accept.getOfferId());
                dto.setGoodsName(accept.getOfferName());
                dto.setIsLatestAccept("T");
                dto.setCateId(accept.getCateId());
                allOfferCollections.stream().forEach(collection -> {
                    if (KiteStringUtils.isEqual(accept.getOfferId(), collection.getOfferId())) {
                        dto.setIsFavorite("T");
                    }
                });
                resultList.add(dto);
            });
        }
        return resultList;
    }

    /**
     * 融合商品关键属性还要标识是哪个单商品
     *
     * @param attrDTOMap
     * @param attrDTO
     */
    private void addAttrDTO(Map<String, AttrDTO> attrDTOMap, AttrDTO attrDTO) {
        if (attrDTOMap.containsKey(attrDTO.getAttrCode())) {
            AttrDTO tempAttrDTO = attrDTOMap.get(attrDTO.getAttrCode());
            tempAttrDTO.setGoodsSku(tempAttrDTO.getGoodsSku() + "," + attrDTO.getGoodsSku());
            List<AttrValuesDTO> attrValuesDTOList = attrDTO.getAttrValues();
            if (KiteListUtils.isNotEmpty(attrValuesDTOList)) {
                List<AttrValuesDTO> tempAttrDTOAttrValues = tempAttrDTO.getAttrValues();
                for (AttrValuesDTO attrValuesDTO : attrValuesDTOList) {
                    boolean isMatch = false;
                    for (AttrValuesDTO tempAttrDTOAttrValue : tempAttrDTOAttrValues) {
                        if (KiteStringUtils.equals(attrValuesDTO.getValueCode(), tempAttrDTOAttrValue.getValueCode())) {
                            tempAttrDTOAttrValue
                                .setGoodsSku(tempAttrDTOAttrValue.getGoodsSku() + "," + attrDTO.getGoodsSku());
                            isMatch = true;
                            break;
                        }
                    }
                    if (!isMatch) {
                        attrValuesDTO.setGoodsSku(attrDTO.getGoodsSku());
                        tempAttrDTOAttrValues.add(attrValuesDTO);
                    }
                }
            }
        }
        else {
            attrDTOMap.put(attrDTO.getAttrCode(), attrDTO);
            if (attrDTO.getAttrValues() == null) {
                attrDTO.setAttrValues(new ArrayList<>());
            }
            else {
                List<AttrValuesDTO> valuesDTOS = attrDTO.getAttrValues();
                valuesDTOS.forEach(attrValuesDTO -> attrValuesDTO.setGoodsSku(attrDTO.getGoodsSku()));
                attrDTO.setAttrValues(valuesDTOS);
            }
        }

    }

    /**
     * 根据sku获取到spu
     *
     * @param goodSku
     * @return
     */
    @Override
    public String getPromotionOfferId(String goodSku) {
        // 获取该销售品的分类
        Map<String, Object> goodsInfoDTO = this.queryGoodsByOfferId(goodSku);
        String promotionOfferId = "";
        if (KiteMapUtils.isNotEmpty(goodsInfoDTO)) {
            String cateId = KiteMapUtils.getString(goodsInfoDTO, "cateId");
            List<String> offerIds = Arrays.asList(goodSku);
            List<GoodsDTO> list = this.queryGoodsListInCategroy(cateId, null);
            if (KiteListUtils.isNotEmpty(list)) {
                if (list.size() == 1) {
                    promotionOfferId = list.get(0).getGoodsSku();
                }
                else {
                    for (GoodsDTO goodsDTO : list) {
                        List<AttrDTO> attrDTOList = this.queryGoodKeyAttrs(goodsDTO.getGoodsSku()).getResultObject();
                        if (KiteListUtils.isEmpty(attrDTOList)) {
                            // 设备类有多个，但无关键属性
                            Map<String, Object> goodsInfo = this.queryGoodsByOfferId(goodsDTO.getGoodsSku());
                            List<Map<String, Object>> saleGoods = KiteMapUtils.getValue(goodsInfo, "saleGoods");
                            if (!KiteListUtils.isEmpty(saleGoods)) {
                                for (Map<String, Object> map : saleGoods) {
                                    String goodsSku = KiteMapUtils.getString(map, "goodsSku");
                                    for (String o : offerIds) {
                                        if (KiteStringUtils.equals(goodsSku, o)) {
                                            promotionOfferId = goodsDTO.getGoodsSku();
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        else {
                            String goodsSkuList = attrDTOList.get(0).getGoodsSku();
                            for (String o : offerIds) {
                                if (goodsSkuList.contains(o)) {
                                    promotionOfferId = goodsDTO.getGoodsSku();
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        return promotionOfferId;
    }

    @Override
    public List<GoodsDTO> queryGoodsListInCategroyCloud(String categroyCode, String goodsName) {
        Map<String, Object> uniBssBody = new HashMap<>();
        Map<String, Object> salegoodslistincategroyReq = new HashMap<>();
        salegoodslistincategroyReq.put("CATEGROY_CODE", categroyCode);
        salegoodslistincategroyReq.put("GOODS_NAME", goodsName);
        salegoodslistincategroyReq.put("ISSALE_GOODS_TYPE", "true");
        salegoodslistincategroyReq.put("TOUCH_POINT", "24");
        salegoodslistincategroyReq.put("province", ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr());
        uniBssBody.put("SALEGOODSLISTINCATEGROY_REQ", salegoodslistincategroyReq);
        Map<String, Object> param = LocalTokenUtil.getParamMap(uniBssBody);
        param.put("OP_CODE", "json_jike_orderCenter_saleGoodsListInCategroy");
        InfServiceHelper.adaptGray(param, salegoodslistincategroyReq);
        String goodsJsonStr;
        if (CallClientUtils.callByHttp()) {
            goodsJsonStr = HttpsCallClient.postStringWithObject(LocalCallClientEnum.INF_COMMON_URL.getCenterCode(),
                LocalCallClientEnum.INF_COMMON_URL.getServiceCode(), param, LocalTokenUtil.getHeaderMap());
        }
        else {
            InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
            goodsJsonStr = infExchangeService.exchange(new JSONObject(param));
        }

        Map<String, Object> goodsMap = JSON.parseObject(goodsJsonStr, Map.class);
        Map<String, Object> resultBodyMap = (Map<String, Object>) goodsMap.get("UNI_BSS_BODY");
        Map<String, String> goodsListInCategroyRsp = (Map<String, String>) resultBodyMap
            .get("SALEGOODSLISTINCATEGROY_RSP");
        List<GoodsDTO> list = JsonUtils
            .parseArray(KiteMapUtils.getString(goodsListInCategroyRsp, "data"), GoodsDTO.class);
        return list;
    }

    @Override
    public List<Map> queryGoodsCategroyLastStageInfo(String goodsProvince) {
        String catJsonStr = getCatJsonStr(goodsProvince);
        Map<String, Object> catMap = JSON.parseObject(catJsonStr, Map.class);
        Map<String, Object> resultBodyMap = (Map<String, Object>) catMap.get("UNI_BSS_BODY");
        Map<String, String> goodsCategroyInfoRsp = (Map<String, String>) resultBodyMap.get("GOODS_CATEGROY_INFO_RSP");
        List<Map> list = Lists.newArrayList();
        if (KiteMapUtils.isNotEmpty(goodsCategroyInfoRsp)) {
            list = JsonUtils.parseArray(goodsCategroyInfoRsp.get("data"), Map.class);
        }
        List<Map> resultList = Lists.newArrayList();
        for (Map map : list) {
            getLastStageInfo(map, resultList);
        }
        // 过滤不需要在商品选择页展示的商品分类（过滤收入归集集团） 收入归集集团需求
        String cateIdNotShow = DcPublicCache
            .getCodea(LocalDcPublicConsts.DC_20210422001, LocalDcPublicConsts.SELECT_GOODS_NOT_SHOW_CATE_ID);
        if (!KiteStringUtils.isEmpty(cateIdNotShow)) {
            List<String> cateIds = Arrays.asList(cateIdNotShow.split(","));
            resultList.removeIf(data -> cateIds.contains(KiteMapUtils.getString(data, "nodeCode")));
        }
        return resultList;
    }

    /**
     * app甩单商品关键属性查询
     * @author zhang.song
     * @date 2021-08-17 18:03
     * @param orderId
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    @Override
    public Map<String, Object> queryAppOrderGoodAttrs(String orderId) {
        Map<String, Object> result = new HashMap<>();

        // 获取订单详情
        IOrderService orderService = SpringUtil.getBean(IOrderService.class);
        Map<String, Object> orderDetailMap = orderService.getOrderDetail(orderId);

        List<Map> goods = CommonUtil.getList(orderDetailMap, "GOODS");
        if (KiteListUtils.isNotEmpty(goods)) {
            String goodsSku = MapUtils.getString(goods.get(0), "SALE_GOODS_CODE");
            String catagoryId = MapUtils.getString(goods.get(0), "CATAGORY_ID");
            String singleGoodsSku = MapUtils.getString(goods.get(0), "CODE");
            if(KiteStringUtils.isEmpty(goodsSku)) {
                goodsSku = this.getPromotionOfferId(singleGoodsSku);
            }

            // 查关键属性
            DataResult<List<AttrDTO>> dataResult = this.queryGoodKeyAttrsByProvince(goodsSku);
            List<AttrDTO> attrList = dataResult.getResultObject();
            if(KiteListUtils.isEmpty(attrList)) {
                // 无关键属性情况，查分类id
                List<GoodsDTO> goodsDTOs = this.queryGoodsListInCategroy(catagoryId, null);
                if(KiteListUtils.isNotEmpty(goodsDTOs)) {
                    goodsDTOs = goodsDTOs.stream().filter(goodsDTO -> KiteStringUtils.isEqual(catagoryId, goodsDTO.getCateId())).collect(Collectors.toList());
                    result.put("goodList", goodsDTOs);
                    result.put("hasKeyAttr", "F");
                }
                return result;
            }

            List<Map> products = CommonUtil.getList(goods.get(0), "PRODUCTS");
            List<Map> attrs = KiteListUtils.isEmpty(products) ? Lists.newArrayList() : Optional.ofNullable(CommonUtil.getList(products.get(0), "ATTRS")).orElse(Lists.newArrayList());

            // 有关键属性情况，设置关键属性默认值
            List<GoodPriceAttrReqDTO> propertyValueList = new ArrayList<>();
            attrList.forEach(attrDTO -> {
                Map attrMap = attrs.stream().filter(map -> KiteStringUtils.isEqual(attrDTO.getAttrCode(), MapUtils.getString(map, "CODE"))).findAny().orElse(null);
                String value = MapUtils.getString(attrMap, "VALUE");
                attrDTO.setDefaultAttrValCodes(value);

                if(KiteStringUtils.isNotEmpty(value)) {
                    GoodPriceAttrReqDTO goodPriceAttrReqDTO = new GoodPriceAttrReqDTO();
                    goodPriceAttrReqDTO.setAttr(attrDTO.getAttrCode());
                    goodPriceAttrReqDTO.setAttrVal(value);
                    propertyValueList.add(goodPriceAttrReqDTO);
                }
            });
            result.put("goodList", attrList);
            result.put("hasKeyAttr", "T");
            result.put("offerId", goodsSku);

            // 所有关键属性均有值，则查询价格
            if(attrList.size() == propertyValueList.size()) {
                GoodPriceReqDTO goodPriceReqDTO = new GoodPriceReqDTO();
                goodPriceReqDTO.setSKU(singleGoodsSku);
                goodPriceReqDTO.setPropertyValue(propertyValueList);
                DataResult<String> priceData = this.queryGoodPrice(goodPriceReqDTO);
                String price = priceData.getResultObject();
                result.put("price", price);
            }
        }
        return result;
    }

    public String getCatJsonStr(String goodsProvince) {
        Map<String, Object> uniBssBody = new HashMap<>();
        Map<String, Object> goodsCategroyInfoReq = new HashMap<>();
        goodsCategroyInfoReq.put("GOODS_PROVINCE", goodsProvince);
        goodsCategroyInfoReq.put("SOURCE_MALL", "24");
        uniBssBody.put("GOODS_CATEGROY_INFO_REQ", goodsCategroyInfoReq);
        Map<String, Object> param = LocalTokenUtil.getParamMap(uniBssBody);
        param.put("OP_CODE", "json_jike_orderCenter_goodsCategroyInfo");
        InfServiceHelper.adaptGray(param, goodsCategroyInfoReq);
        String catJsonStr;
        if (CallClientUtils.callByHttp()) {
            catJsonStr = HttpsCallClient.postStringWithObject(LocalCallClientEnum.INF_COMMON_URL.getCenterCode(),
                LocalCallClientEnum.INF_COMMON_URL.getServiceCode(), param, LocalTokenUtil.getHeaderMap());
        }
        else {
            InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
            catJsonStr = infExchangeService.exchange(new JSONObject(param));
        }
        return catJsonStr;
    }

    public List getLastStageInfo(Map map, List<Map> resultList) {
        List<Map> childs = (List) map.get("child");
        if (KiteListUtils.isNotEmpty(childs)) {
            for (Map child : childs) {
                resultList = getLastStageInfo(child, resultList);
            }
        }
        else {
            resultList.add(map);
        }
        return resultList;
    }

    /**
     * 选择商品页面，不显示配置的商品分类id
     * @author zhang.song
     * @date 2021-07-14 15:26
     * @param list
     * @return void
     */
    private void removeNotShowGoods(List<GoodsCategroyInfoDTO> list) {
        // 过滤不需要在商品选择页展示的商品分类（过滤收入归集集团） 收入归集集团需求
        if(KiteListUtils.isNotEmpty(list)) {
            String cateIdNotShow = DcPublicCache.getCodea(LocalDcPublicConsts.DC_20210422001, LocalDcPublicConsts.SELECT_GOODS_NOT_SHOW_CATE_ID);
            if(KiteStringUtils.isNotEmpty(cateIdNotShow)) {
                String[] removeIdArr = cateIdNotShow.split(SymbolConsts.COMMA);
                // 删除前端选择商品页面不显示的商品分类id
                removeGoodCateId(list, removeIdArr);
            }
        }
    }
    private static void removeGoodCateId(List<GoodsCategroyInfoDTO> child, String[] removeIdArr) {
        for (int i = child.size() - 1; i >= 0 ; i--) {
            if(KiteStringUtils.equalsAny(child.get(i).getNodeCode(), removeIdArr)) {
                child.remove(i);
                continue;
            }

            List<GoodsCategroyInfoDTO> child2 = child.get(i).getChild();
            if(KiteListUtils.isNotEmpty(child2)) {
                removeGoodCateId(child2, removeIdArr);
            }
        }
    }
    public static void packInValidMemCate(List<Map> members_his, List<GoodsMemberDTO> goodsMemberDTOList) {
        if(KiteListUtils.isNotEmpty(members_his)){
            Map memberGrp = new HashMap();
            memberGrp.put("memberName","历史附加产品分组");
            memberGrp.put("memberType","additional");
            memberGrp.put("statusCd",KeyConsts2.PROD_STATUS_HIS_00C);
            memberGrp.put("memberGoods",members_his);
            goodsMemberDTOList.add(JsonUtils.parseObject(JSON.toJSONString(memberGrp), GoodsMemberDTO.class));
        }
    }
}
